package com.qf.cs2203Spring07.service.Impl;

import com.qf.cs2203Spring07.aop.anno.Retry;
import com.qf.cs2203Spring07.common.AppException;
import com.qf.cs2203Spring07.common.ReTryException;
import com.qf.cs2203Spring07.entity.Account;
import com.qf.cs2203Spring07.mapper.AccountMapper;
import com.qf.cs2203Spring07.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.SQLException;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    @Transactional
    public Account queryById(String id, String password) throws SQLException {
        Account account = accountMapper.selectByPrimaryKey(id);
        if (account == null) {
            throw new AppException("301", "账号不存在");
        }
        System.out.println(account.getState().toString());
        if (!password.equals(account.getPassword())) {
            throw new AppException("302", "账号或者密码错误");
        }
        if (account.getState().toString().equals("1")) {
            System.out.println("123456789");
            throw new AppException("303", "账号已被冻结");
        }
        return account;
    }

    @Override
    @Transactional
    @Retry(CLASS = ReTryException.class,RetryNum = 20)
    public Integer getMoney(String id, BigDecimal money) throws Exception {
        Account account = accountMapper.selectByPrimaryKey(id);
        Integer i = 0;
        if (account == null) {
            throw new AppException("301", "账号不存在");
        }
        //System.out.println(account.getState().toString());
        if (account.getState().toString().equals("1")) {
            System.out.println("123456789");
            throw new AppException("303", "账号已被冻结");
        }
        if(account.getMoney().compareTo(money)<0) {
            throw new AppException("304","余额不足");
        }
//        int i = accountMapper.updateByPrimaryKeySelective(Account.builder().cid(id).money(account.getMoney().subtract(money)).build());
        i = accountMapper.updateMoneyByqu(id, BigDecimal.ZERO.subtract(money), account.getVersion());
//        int j = 1/0;
        if (i == 0){
            throw new ReTryException("305","取钱失败，请重新操作");
        } else {
            System.out.println(Thread.currentThread().getName()+"取钱成功" +account.getCid());
        }
        return i;
    }
}
